/*
 * @Author: YuWuChen82 1813109877@qq.com
 * @Date: 2025-07-20
 * @LastEditors: YuWuChen82 1813109877@qq.com
 * @LastEditTime: 2025-07-21
 * @FilePath: \antd-demo\src\store\modules\user.js
 * @Description: 
 */
//用户模块
import { createSlice } from '@reduxjs/toolkit'
import { setToken as setTokenByUtils, getToken,removeToken } from '@/utils'
import { loginAPI,getProfileAPI } from '@/apis/user'
const userStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    //同步操作
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload
            setTokenByUtils(action.payload)
        },
        setUserInfo: (state, action) => {
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    

    },

})
//解构出actionCreater
const { setToken, setUserInfo,clearUserInfo } = userStore.actions

//获取reducer函数
const userReducer = userStore.reducer

//异步操作登录
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        //1.发送异步请求
        const res = await loginAPI(loginForm)
        //2.提交同步action进行token存入
        dispatch(setToken(res.data.token))
    }
}

//异步获取个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
          //1.发送异步请求
          const res = await getProfileAPI()
          //2.提交同步action进行
          dispatch(setUserInfo(res.data))
    }
}

export { setToken, fetchLogin,fetchUserInfo,clearUserInfo }
export default userReducer
